package org.example.ams.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.ams.dao.system.ISysUserRoleDao;
import org.example.ams.entity.system.SysUserRole;
import org.example.ams.service.system.ISysUserRoleService;
import org.example.common.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


@Service
public class SysUserRoleServiceImpl implements ISysUserRoleService {

    @Autowired
    private ISysUserRoleDao sysUserRoleDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void add(Integer userId,Integer[] roleIds) {
        SysUserRole sysUserRole = new SysUserRole();
        if(roleIds.length > 0) {
            // 1. 分配角色
            for (Integer roleId : roleIds) {
                sysUserRole.setUserId(userId).setRoleId(roleId);
                sysUserRoleDao.insert(sysUserRole);
            }
            // 2. 缓存更新策略 - 删除缓存
            redisTemplate.delete(RedisConstant.NAV_TREE_KEY);
        }
    }

    @Override
    public void deleteAll(Integer userId) {
        sysUserRoleDao.delete(new QueryWrapper<SysUserRole>().eq("user_id",userId));
    }

    @Override
    public void deleteByUserIdAndRoleId(Integer userId, Integer roleId) {
        sysUserRoleDao.delete(new QueryWrapper<SysUserRole>().eq("user_id",userId).eq("role_id",roleId));
        // 删除导航缓存
        redisTemplate.delete(RedisConstant.NAV_TREE_KEY);
    }
}
